package com.zc.study.designPattern.创建型设计模式.singletonPattern;

/**
 * 懒汉模式(延迟加载)
 */
public class MyObject {
    private static volatile MyObject myObject;
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    private MyObject() {
    }

    public static MyObject getInstance() {
        if (myObject == null) {
            synchronized (MyObject.class) {
                //双重检查机制,避免并发时重复new对象(业务复杂会出现),对象上需加volatile关键字,实现资源可见
                if(myObject == null){
                    myObject = new MyObject();
                }
            }
        }
        return myObject;
    }
}
